package com.why.aop;

import cn.hutool.json.JSONUtil;
import com.why.entity.Log;
import com.why.entity.User;
import com.why.mapper.LogMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author hy woo
 * @date 2022/6/7 23:39
 */
@Component
@Aspect
public class MyAspect {

    @Autowired
    HttpServletRequest request;
    @Autowired
    LogMapper logMapper;

    @Before("@annotation(com.why.aop.LogAnn)")
    public void before(JoinPoint joinPoint){
        Log log = new Log();
        log.setAcesstime(LocalDateTime.now());
        log.setFromip(request.getRemoteAddr()); // ip
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof User){
            String username = ((User)principal).getUsername();
            log.setUsername(username);
        }else {
            log.setUsername("匿名用户");
        }
        log.setUrl(request.getRequestURI());
        String param = JSONUtil.toJsonStr(joinPoint.getArgs());
        log.setUrlpara(param);
        logMapper.insert(log);
    }
}
